<?php
$otppasswdFile = '/etc/otppasswd';
$otpstateDir = '/etc/otpstate';
$otptokensFile = '/etc/otptokens';

$radius_clientsFile = '/etc/freeradius/clients.conf';
$radius_usersFile = '/etc/freeradius/users';

if( is_file('/usr/sbin/resynctool') ) {
	$resynctool_bin = '/usr/sbin/resynctool';
}
else if ( is_file('/usr/local/sbin/resynctool') ) {
	$resynctool_bin = '/usr/local/sbin/resynctool';
}
else {
	//ERROR: kan ej hitta resynctool, testar ändå...
	$resynctool_bin = 'resynctool';
}


function dousers()
{
	global $otppasswdFile;
	global $otptokensFile;
	global $otpstateDir;
	global $GET;

	//Skapa kopplingsarray mellan användare -> token-key & token-key -> användare
	$otppasswd_arr = file($otppasswdFile);
	foreach($otppasswd_arr AS $otppasswd_line) {
		preg_match('/^([^:^\s]*):([^:^\s]*):([^:^\s]*)/', $otppasswd_line, $match);
		$user2key[$match[1]] = $match[3];
		$key2user[$match[3]] = $match[1];
	}

	//Skapa kopplingsarray mellan token-key -> token-eid
	$otptokens_arr = file($otptokensFile);
	foreach($otptokens_arr AS $otptokens_line) {
		preg_match('/^([^:^\s]*):([^:^\s]*):/', $otptokens_line, $match);
		$key2eid[$match[2]] = $match[1];
		$eid2key[$match[1]] = $match[2];
	}

//Om ny användare ska skapas
	if( isset($_POST['b_new']) &&
	  isset($_POST['username']) && isset($_POST['eid']) && isset($_POST['pin']) ) {
		$username = trim($_POST['username']);
		$eid = trim($_POST['eid']);
		$pin = trim($_POST['pin']);

		//Kontrollera indata
		$error = false;
		if( preg_match('/^[a-zåäöA-ZÅÄÖ0-9_]+$/', $username) == 0 ) {
			error('username');
			$error = true;
		}
		else if( ! isset($eid2key[$eid]) ) {
			error('eid_invalid');
			$error = true;
		}
		else if( isset($key2user[$eid2key[$eid]]) ) {
			error('eid_taken');
			$error = true;
		}

		// Om inga fel sparas användaren
		if( ! $error ) {
			$key = $eid2key[$eid];		
			$pin_ascii = '';
			if( strlen($pin) > 0 ) {
				foreach(str_split($pin) AS $char)
					$pin_ascii .= dechex(ord($char));
				$otppasswd_line = "$username:hotp-d6:$key:".$pin_ascii."\n";
			}
			else {
				$otppasswd_line = "$username:hotp-d6:$key\n";
			}
			
			file_put_contents($otppasswdFile, $otppasswd_line, FILE_APPEND);
			$GET['sync'] = '1';  //Nästa Uggla-sida ska vara sync
			$GET['user'] = $username;
			$GET['eid'] = $eid;

			info('user_added');
		}
	}

//Om användare ska raderas
	if( isset($_GET['del']) 
	  && $_GET['del'] == 'user' && isset($_GET['user']) ) {
		$user = trim($_GET['user']);
		$otppasswd_old = file_get_contents($otppasswdFile);
		
		$otppasswd_new = preg_replace("/^($user\:\S*\s*)/m",'', $otppasswd_old);
		file_put_contents($otppasswdFile, $otppasswd_new);

		//Radera state-data
		if( is_file("$otpstateDir/$user") ) {
			unlink("$otpstateDir/$user");
		}

		info('user_removed');
	}
}


function dotokensync()
{
	global $resynctool_bin;
	global $otptokensFile;
	global $otpstateDir;
	global $GET;

	$user = trim($_GET['user']);
	$eid = trim($_GET['eid']);
	$pass1 = trim($_POST['pass1']);
	$pass2 = trim($_POST['pass2']);

	//Skapa kopplingsarray mellan token-key -> token-eid
	$otptokens_arr = file($otptokensFile);
	foreach($otptokens_arr AS $otptokens_line) {
		preg_match('/^([^:^\s]*):([^:^\s]*):/', $otptokens_line, $match);
		$eid2key[$match[1]] = $match[2];
	}
	$key = $eid2key[$eid];

	exec("$resynctool_bin -1 $pass1 -2 $pass2 -u \"$user\" -k $key 2> /dev/null", $out, $ret);
	if( $ret == 0 ) {
		preg_match('/^([^:]*:[^:]*:0*)([^:]*)(:.*)/', $out[0], $match);
		$nr = dechex(hexdec($match[2])-1);
		$new_line = $match[1].$nr.$match[3]."\n";
		file_put_contents("$otpstateDir/$user", $new_line);
		info('sync_done');
	}
	else {
		$GET['sync'] = '1';
		$GET['user'] = $user;
		$GET['eid'] = $eid;

		error('sync_error');
	}
}


function dosettings()
{
	global $radius_clientsFile;
	global $radius_usersFile;

	$clients_conf = file_get_contents($radius_clientsFile);

	if( preg_match('@^# Uggla wwwadmin\s*client\s*([^/]*)/32\s*\{\s*secret\s*=\s*([^\s]*)\s*shortname\s*=\s*([^\s]*)\s*}@m', $clients_conf, $match) != 0
	  && isset($_POST['ip']) && isset($_POST['key']) ) {
		$billion_ip = trim($_POST['ip']);
		$key = trim($_POST['key']);
		$shortname = 'billion-ssl-vpn';

		//Uppdatera clients.conf-fil
		$confpart_new = "# Uggla wwwadmin\n";
		$confpart_new .= "client $billion_ip/32 {\n";
		$confpart_new .= "\tsecret = $key\n";
		$confpart_new .= "\tshortname = $shortname\n";
		$confpart_new .= "}\n";

		$clients_conf_new = preg_replace('@^(# Uggla wwwadmin\s*client\s*[^/]*/32\s*\{\s*secret\s*=\s*[^\s]*\s*shortname\s*=\s*[^\s]*\s*})@m', $confpart_new, $clients_conf);

		file_put_contents($radius_clientsFile, $clients_conf_new);

		// Uppdatera users-fil
		$users = file_get_contents($radius_usersFile);
		$userspart_new = "# Uggla wwwadmin\n";
		$userspart_new .= "DEFAULT Client-IP-Address == \"$billion_ip\", Auth-Type := otp\n";

		$users_new = preg_replace('@^(# Uggla wwwadmin\s*DEFAULT\s*Client-IP-Address\s*==\s*")([^"]*)(",\s*Auth-Type\s*\:=\s*otp\s*)@m', $userspart_new, $users);

		file_put_contents($radius_usersFile, $users_new);

		

		info('info_saved');
	}
}

//////////////////////////////////////////


switch( $_GET['t'] ) {
default:
case 'users':
	if( isset($_GET['sync']))
		dotokensync();
	else
		dousers();
	break;
case 'tokens':
 	dotokens();
	break;
case 'import':
	doimport();
	break;
case 'settings':
	dosettings();
	break;
}
?>
